<?php

require_once '/home/clients/advsm_ftp0/domains/vkposter.com/html/classes/Bootstrap.php';

$vk = vk::getInstance();
$user = new VkUser(14754193);

$groups = array(33342326, 37961117, 33375244, 36904054, 37959473);

foreach ($groups as $groupId) {
$query = array(
    'owner_id' => '-' . $groupId,
    'offset' => 0,
    'count' => 7,
    'filter' => 'all',
    'access_token' => $user->getAccessToken()
);
        
$posts = $vk->api('wall.get', $query);
unset($posts[0]);
foreach ($posts as $post) {
	if ($post['comments']['count'] == 0) {
		continue;
	}
	
	$query = array(
    	'owner_id' => '-' . $groupId,
    	'access_token' => $user->getAccessToken(),
    	'preview_length' => 0,
    	'sort' => 'asc',
    	'post_id' => $post['id'],
    	'count' => 10,
	);
	
	$comments = $vk->api('wall.getComments', $query);
	unset($comments[0]);
	foreach ($comments as $comment) {
		if (!isSpam($comment['text'])) {
			continue;
		}
		
		$query = array(
			'owner_id' => '-' . $groupId,
			'cid' => $comment['cid'],
			'access_token' => $user->getAccessToken(),
		);
		$result = $vk->api('wall.deleteComment', $query);
		
		$row = SpamDetectedPeer::getInstance()->createRow();
		$row->setGroupId($groupId);
		$row->setPostId($post['id']);
		$row->setPostUrl("http://vk.com/wall-{$groupId}_{$post['id']}");
		$row->setText($comment['text']);
		$row->save();
	}
}


}


/**
 * Пытается понять, является ли сообщение спамом.
 *
 * @return boolean
 */
function isSpam($text)
{
	if (stripos($text, 'http://') !== false) {
		return true;
	}
	
	if (stripos($text, 'vk.com/') !== false) {
		return true;
	}
	
	if (preg_match('/[a-z0-9\-]{2,20}\.[a-z]{2,4}/is', $text, $matches)) {
		return true;
	}
	
	return false;
}

die();

$_adapter = Zend_Db_Table_Abstract::getDefaultAdapter();
		
$writer = new Zend_Log_Writer_Db($_adapter, 'log');

$log = new Log($writer);

$select = TurnPostPeer::getInstance()->select();
$select->where('post_date <= ?', $currentDay)
        ->where('post_time <= ?', $currentTime)
        ->where('is_posted = ?', 0);

$posts = TurnPostPeer::getInstance()->fetchAll($select);

if ($posts->count()) {
    foreach($posts as $post){
        $user = $post->getUserRowByUserId();
        $turn = $post->getTurnRowByTurnId();
        $group = $turn->getGroupsRowByGroupId();
        $vk = vk::getInstance();

        // РїРѕР»СѓС‡Р°РµРј СЃРµСЂРІРµСЂ РґР»СЏ СЃРѕС…СЂР°РЅРµРЅРёСЏ С„РѕС‚РѕРіСЂР°С„РёРё
        $data = array(
            'gid' => $group->vk_id,
            'access_token' => $user->access_token
        );

        $serverPhoto = $vk->api('photos.getWallUploadServer', $data);
        $log->info('Crone run trunks: vk api request (photos.getWallUploadServer) params (' . $vk->getStrParams() . '); response=' . $vk->getStrResponse());

        // СЃРѕС…СЂР°РЅРµСЏРµРј С„РѕС‚РєСѓ РЅР° СЃРµСЂРІРµСЂРµ VK
        /*$uploadUrl = Zend_Uri::factory($serverPhoto['upload_url']);
        $client = new Zend_Http_Client($uploadUrl);
        $image = $post->image;
        if(false === strpos($image, 'http://')){
            if ($qp = strpos($image, '?')) {
                $image = $_SERVER['DOCUMENT_ROOT'] . substr($image, 0, $qp);
            } else {
                $image = $_SERVER['DOCUMENT_ROOT'] . $image;
            }
        }
        $client->setFileUpload($image, 'photo');
        $result = $client->request('POST');
        $response = Zend_Json::decode($result->getBody());*/
        
        $image = $post->image;
        if (strpos($image, 'http://') !== false) {
            // СЃРєР°С‡РёРІР°РµРј РєР°СЂС‚РёРЅРєСѓ
            $filePutResult = file_put_contents('/home/clients/advsm_ftp0/domains/vkposter.com/html/images/post/'.$post->post_id.'.jpg', file_get_contents($image));
            if ($filePutResult == false) {
                $log->err('Crone run trunks: error download image of ' . $image . ' in /home/clients/advsm_ftp0/domains/vkposter.com/html/images/post/'.$post->post_id.'.jpg');
                throw new Exception('Crone run trunks: error download image of ' . $image . ' in /home/clients/advsm_ftp0/domains/vkposter.com/html/images/post/'.$post->post_id.'.jpg');
            }
            $image = '/images/post/'.$post->post_id.'.jpg';
        } else {
            if (strpos($image, '?') !== false) {
                $image = substr($image, 0, strpos($image, '?'));
            }            
        }
        $image = '/home/clients/advsm_ftp0/domains/vkposter.com/html' . $image;
        
        $log->info('Crone run trunks: image path ' . $image);
        $post_data = array('photo' => '@' . $image);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $serverPhoto['upload_url']);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $response = curl_exec($curl);
        if ($response === FALSE) {
            $log->err('Crone run trunks: upload foto ' . curl_error($curl));
            throw new Exception('Crone run trunks: upload foto ' . curl_error($curl));
        }
        curl_close($curl);
        
        $log->info('Crone run trunks: response ' . $response . ' upload image ' . $image . ' in ' . $serverPhoto['upload_url']);
        
        $response = Zend_Json::decode($response);
        
        // С„РѕСЂРјРёСЂСѓРµРј РґР°РЅРЅС‹Рµ
        $data = array(
            'gid' => $group->vk_id,
            'server' => $response['server'],
            'photo' => $response['photo'],
            'hash' => $response['hash'],
            'access_token' => $user->access_token
        );
        // СЃРѕС…СЂР°РЅСЏРµРј РєР°СЂС‚РёРЅРєСѓ
        $wallPhoto = $vk->api('photos.saveWallPhoto', $data);
        $log->info('Crone run trunks: vk api request (photos.saveWallPhoto) params (' . $vk->getStrParams() . '); response=' . $vk->getStrResponse());

        // РїРѕСЃС‚РёРј
        $data = array(
            'owner_id' => '-' . $group->vk_id,
            'attachments' => $wallPhoto[0]['id'],
            'message' => $post->text,
            'from_group' => 1,
            'signed' => 0,
            'access_token' => $user->access_token
        );

        $wall = $vk->api('wall.post', $data);

        $log->info('Crone run trunks: vk api request (wall.post) params (' . $vk->getStrParams() . '); response=' . $vk->getStrResponse());

        PostPeer::getInstance()->updatePost(
            new VkUser($user->vk_id),
            $post->post_id,
            $post->text,
            $wallPhoto[0]['id'],
            'http://vk.com/wall-' . $group->vk_id . '_' . $wall['post_id']
        );

        $postRow = TurnPostPeer::getInstance();
        $postRow->update(array('is_posted'=>1), 'id = ' . $post->id);
        $log->info('Crone run trunks: DB update post ' . $post->post_id);
    }
}
